Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 | /** * BillingController.js * * Handles billing and subscription management endpoints * Manages Stripe/PayPal integrations, subscriptions, and usage tracking * * @module controllers/BillingController */ const BaseController = require('./BaseController'); const BillingService = require('../services/BillingService'); const { pool } = require('../config/database'); const logger = require('../config/logger'); const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY); class BillingController extends BaseController { /** * Create a new subscription * POST /api/billing/subscribe */ static async subscribe(req, res) { const connection = await pool.getConnection(); try { const { planId, paymentMethodId, paymentGateway = 'stripe' } = req.body; const tenantId = req.user.tenantId; // Validate input if (!planId || !paymentMethodId) { return res.status(400).json({ success: false, message: req.t('validation.required_fields') }); } // Check if tenant already has active subscription const [existing] = await connection.query( `SELECT * FROM subscriptions WHERE tenant_id = ? AND status IN ('active', 'trialing')`, [tenantId] ); if (existing.length) { return res.status(400).json({ success: false, message: req.t('billing.already_subscribed') }); } // Create subscription based on gateway let result; if (paymentGateway === 'stripe') { result = await BillingService.createStripeSubscription( tenantId, planId, paymentMethodId ); } else { return res.status(400).json({ success: false, message: req.t('billing.invalid_gateway') }); } logger.info(`Subscription created for tenant ${tenantId}`); res.json({ success: true, message: req.t('billing.subscription_created'), data: result }); } catch (error) { logger.error('Error creating subscription:', error); res.status(500).json({ success: false, message: req.t('errors.internal_server_error'), error: error.message }); } finally { connection.release(); } } /** * Cancel subscription * POST /api/billing/cancel */ static async cancelSubscription(req, res) { try { const { immediately = false } = req.body; const tenantId = req.user.tenantId; const result = await BillingService.cancelStripeSubscription( tenantId, immediately ); logger.info(`Subscription canceled for tenant ${tenantId}`); res.json({ success: true, message: req.t('billing.subscription_canceled'), data: result }); } catch (error) { logger.error('Error canceling subscription:', error); res.status(500).json({ success: false, message: req.t('errors.internal_server_error'), error: error.message }); } } /** * Update subscription plan * PUT /api/billing/plan */ static async updatePlan(req, res) { try { const { planId } = req.body; const tenantId = req.user.tenantId; if (!planId) { return res.status(400).json({ success: false, message: req.t('validation.required_fields') }); } const result = await BillingService.updateSubscriptionPlan( tenantId, planId ); logger.info(`Subscription plan updated for tenant ${tenantId}`); res.json({ success: true, message: req.t('billing.plan_updated'), data: result }); } catch (error) { logger.error('Error updating plan:', error); res.status(500).json({ success: false, message: req.t('errors.internal_server_error'), error: error.message }); } } /** * Get current subscription details * GET /api/billing/subscription */ static async getSubscription(req, res) { const connection = await pool.getConnection(); try { const tenantId = req.user.tenantId; const [subscriptions] = await connection.query( `SELECT s.*, sp.name as plan_name, sp.price, sp.currency, sp.max_messages_per_month, sp.max_users, sp.features FROM subscriptions s JOIN subscription_plans sp ON s.plan_id = sp.id WHERE s.tenant_id = ? ORDER BY s.created_at DESC LIMIT 1`, [tenantId] ); if (!subscriptions.length) { return res.status(404).json({ success: false, message: req.t('billing.no_subscription') }); } const subscription = subscriptions[0]; // Parse features if stored as JSON if (subscription.features && typeof subscription.features === 'string') { subscription.features = JSON.parse(subscription.features); } res.json({ success: true, data: subscription }); } catch (error) { logger.error('Error getting subscription:', error); res.status(500).json({ success: false, message: req.t('errors.internal_server_error'), error: error.message }); } finally { connection.release(); } } /** * Get usage statistics * GET /api/billing/usage */ static async getUsage(req, res) { try { const tenantId = req.user.tenantId; const { months = 6 } = req.query; const stats = await BillingService.getUsageStats(tenantId, parseInt(months)); const current = await BillingService.trackMessageUsage(tenantId, 0); res.json({ success: true, data: { current: current, history: stats } }); } catch (error) { logger.error('Error getting usage:', error); res.status(500).json({ success: false, message: req.t('errors.internal_server_error'), error: error.message }); } } /** * Get payment history * GET /api/billing/payments */ static async getPayments(req, res) { const connection = await pool.getConnection(); try { const tenantId = req.user.tenantId; const { page = 1, limit = 20 } = req.query; const offset = (page - 1) * limit; const [payments] = await connection.query( `SELECT p.*, sp.name as plan_name FROM payments p LEFT JOIN subscriptions s ON p.subscription_id = s.id LEFT JOIN subscription_plans sp ON s.plan_id = sp.id WHERE p.tenant_id = ? ORDER BY p.created_at DESC LIMIT ? OFFSET ?`, [tenantId, parseInt(limit), offset] ); const [countResult] = await connection.query( 'SELECT COUNT(*) as total FROM payments WHERE tenant_id = ?', [tenantId] ); res.json({ success: true, data: payments, pagination: { page: parseInt(page), limit: parseInt(limit), total: countResult[0].total, pages: Math.ceil(countResult[0].total / limit) } }); } catch (error) { logger.error('Error getting payments:', error); res.status(500).json({ success: false, message: req.t('errors.internal_server_error'), error: error.message }); } finally { connection.release(); } } /** * Get available plans * GET /api/billing/plans */ static async getPlans(req, res) { const connection = await pool.getConnection(); try { const [plans] = await connection.query( `SELECT * FROM subscription_plans WHERE is_active = 1 ORDER BY price ASC` ); // Parse features JSON plans.forEach(plan => { if (plan.features && typeof plan.features === 'string') { plan.features = JSON.parse(plan.features); } }); res.json({ success: true, data: plans }); } catch (error) { logger.error('Error getting plans:', error); res.status(500).json({ success: false, message: req.t('errors.internal_server_error'), error: error.message }); } finally { connection.release(); } } /** * Create Stripe setup intent for payment method * POST /api/billing/setup-intent */ static async createSetupIntent(req, res) { const connection = await pool.getConnection(); try { const tenantId = req.user.tenantId; // Get tenant details const [tenants] = await connection.query( 'SELECT * FROM tenants WHERE id = ?', [tenantId] ); if (!tenants.length) { return res.status(404).json({ success: false, message: req.t('errors.tenant_not_found') }); } const tenant = tenants[0]; // Get or create Stripe customer let customerId = tenant.stripe_customer_id; if (!customerId) { const customer = await BillingService.createStripeCustomer(tenant); customerId = customer.id; await connection.query( 'UPDATE tenants SET stripe_customer_id = ? WHERE id = ?', [customerId, tenantId] ); } // Create setup intent const setupIntent = await stripe.setupIntents.create({ customer: customerId, payment_method_types: ['card'] }); res.json({ success: true, data: { clientSecret: setupIntent.client_secret } }); } catch (error) { logger.error('Error creating setup intent:', error); res.status(500).json({ success: false, message: req.t('errors.internal_server_error'), error: error.message }); } finally { connection.release(); } } /** * Handle Stripe webhook * POST /api/billing/webhook/stripe */ static async stripeWebhook(req, res) { const sig = req.headers['stripe-signature']; const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET; try { // Verify webhook signature const event = stripe.webhooks.constructEvent( req.body, sig, webhookSecret ); // Handle the event await BillingService.handleStripeWebhook(event); res.json({ received: true }); } catch (error) { logger.error('Stripe webhook error:', error); res.status(400).json({ success: false, message: `Webhook Error: ${error.message}` }); } } /** * Get invoice by ID * GET /api/billing/invoice/:id */ static async getInvoice(req, res) { const connection = await pool.getConnection(); try { const { id } = req.params; const tenantId = req.user.tenantId; const [payments] = await connection.query( `SELECT p.*, sp.name as plan_name, t.company_name, t.email FROM payments p LEFT JOIN subscriptions s ON p.subscription_id = s.id LEFT JOIN subscription_plans sp ON s.plan_id = sp.id LEFT JOIN tenants t ON p.tenant_id = t.id WHERE p.id = ? AND p.tenant_id = ?`, [id, tenantId] ); if (!payments.length) { return res.status(404).json({ success: false, message: req.t('billing.invoice_not_found') }); } res.json({ success: true, data: payments[0] }); } catch (error) { logger.error('Error getting invoice:', error); res.status(500).json({ success: false, message: req.t('errors.internal_server_error'), error: error.message }); } finally { connection.release(); } } } module.exports = BillingController; |